package com.samxcode.leetcode;

/**
 * You are given two linked lists representing two non-negative numbers. The digits are stored in
 * reverse order and each of their nodes contain a single digit. Add the two numbers and return it
 * as a linked list.
 * 
 * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8
 * 
 * 
 * Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode(int
 * x) { val = x; next = null; } }
 */
public class AddTwoNumbers {

    public class ListNode {
        int val;
        ListNode next;


        ListNode(int x) {
            val = x;
            next = null;
        }
    }


    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode node = null;
        ListNode preNode = head;
        int carryAdd = 0;    //the add carry
        int value = 0;
        while (l1 != null && l2 != null) {
            value = l1.val + l2.val + carryAdd;
            node = new ListNode(value % 10);
            preNode.next = node;
            preNode = node;
            if (value > 9) {
                carryAdd = 1;
            } else {
                carryAdd = 0;
            }
            l1 = l1.next;
            l2 = l2.next;
        }
        //if l1 or l2 not reach end
        ListNode l = l1 == null ? l2 : l1;
        while (l != null) {
            value = l.val + carryAdd;
            node = new ListNode(value % 10);
            preNode.next = node;
            preNode = node;
            if (value > 9) {
                carryAdd = 1;
            } else {
                carryAdd = 0;
            }
            l = l.next;
        }
        if (carryAdd == 1) {
            node = new ListNode(1);
            preNode.next = node;
        }
        return head.next;
    }

}
